package rensoft.portfolio.client.lib.view;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.IFrameElement;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HasHTML;

import rensoft.gwt.client.view.View;



public class CKEditor extends View<Frame> {
  private final HasHTML hashtml;
  private final ClosableDialogCaption caption = new ClosableDialogCaption();
  private final DialogBox dialog = new DialogBox(caption) {
    @Override
    public void hide(boolean autoClosed) {
      onEditorClose();
      super.hide(autoClosed);
    }
  };

  public CKEditor(HasHTML hashtml) {
    initWidget(new Frame());
    this.hashtml = hashtml;
    widget().setUrl("ckeditor/editor.html");
    setSize(700, 450);
  }

  public void show() {
    publisHtmlForEditor(hashtml.getHTML());
    caption.setDialog(dialog);
    dialog.setWidget(widget());
    dialog.center();
  }

  private native final String getEditorHtml(Document document)/*-{
		return document.body.getEditorHtml();
  }-*/;

  private void onEditorClose() {
    Document doc = IFrameElement.as(widget().getElement()).getContentDocument();
    hashtml.setHTML(getEditorHtml(doc));
  }

  private native final void publisHtmlForEditor(String html)/*-{
		$doc.body.ckeditorhtml = html;
  }-*/;
}
